//
//  ParkDetailViewController.m
//  HundPark
//
//  Created by Aguilar Rolando on 2013-03-04.
//  Copyright (c) 2013 ARV IT. All rights reserved.
//

#import "ParkDetailViewController.h"



@interface ParkDetailViewController ()
{
    DogParkClient *client;

}

@property (weak, nonatomic) NSString *UUID;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

@end

@implementation ParkDetailViewController

@synthesize parkImage = _parkImage;
@synthesize park = _park;
@synthesize txtViewParkInfo = _txtViewParkInfo;
@synthesize UUID = _UUID;
@synthesize checkInButton = _checkInButton;
@synthesize activityIndicator =_activityIndicator;

#define GETCHECKIN @"HundApp.php?method=getCheckIn"
#define FILESERVERURL @"http://www.arvit.se/parkImages/"

// Lazy Instantiation
-(NSString *)UUID
{
    if(!_UUID){
        
        //Load from NSUserDeafults
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *UUIDString = [defaults objectForKey:@"appUUIDKey"];
        _UUID = UUIDString;
    }
    return _UUID;
}

#pragma mark - Life cycle

-(void)viewWillAppear:(BOOL)animated
{
    client = [DogParkClient sharedClient];
    client.delegate = self;
    [self checkStatus];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // now set your Custom label
    CustomNavbarTitleLabelGreen *titleLabel =[[CustomNavbarTitleLabelGreen alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
    titleLabel.text = self.park.name;
    self.navigationItem.titleView = titleLabel;
    self.txtViewParkInfo.text = self.park.info;
    [self getImageFromFileServer];
}

- (void)viewDidUnload
{
    [self setParkImage:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)getImageFromFileServer {
    
    [self.activityIndicator startAnimating];
    
    NSString *imageUrl = [NSString stringWithFormat:@"%@%@.png",FILESERVERURL,self.park.parkId];
    NSURL *url = [NSURL URLWithString:imageUrl];
    
    AFImageRequestOperation* imageOperation =
    [AFImageRequestOperation imageRequestOperationWithRequest: [NSURLRequest requestWithURL:url]
                                                      success:^(UIImage *image) {
                                                          self.parkImage.image = image;
                                                          [self.activityIndicator stopAnimating];
                                                      }];
    // TODO: Just one image do need a operation queue?
    //NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    //[queue addOperation:imageOperation];
     [imageOperation start];
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showParkInMap"]) {
        AllParksMapViewController *parkMapViewController = segue.destinationViewController;
        parkMapViewController.park = self.park;
    }
}

#pragma mark - Actions
- (IBAction)checkIn:(UIButton *)sender {
    [self checkIn];
}

- (void)checkIn {
    NSString *checkIn = (self.checkInButton.selected) ? @"NO" : @"YES";
    
    // Get check info (UID and park ID) to send to server as JSON
    NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:self.UUID,@"UUID",self.park.parkId,@"parkId",checkIn,@"checkIn",nil];
    [client updateStatusAtPark:dic];
    
}

-(void)dogParkClient:(DogParkClient *)client didUpdateStatus:(id)responseObject{
    // Parse json
    NSLog(@"%@",responseObject);
    
    NSArray *results = responseObject;
    NSDictionary *parkIdDic = [results objectAtIndex:0];
    
    // Check if checked in or not
    if ([parkIdDic[@"checkIn"] isEqualToString:@"YES"])
    {
        [self.checkInButton setTitle:@"Vovve Inne!" forState:UIControlStateSelected];
        self.checkInButton.selected = YES;
    }
    else if ([parkIdDic[@"checkIn"] isEqualToString:@"NO"])
    {
        [self.checkInButton setTitle:@"Check In Vovve?" forState:UIControlStateNormal];
        self.checkInButton.selected = NO;
    }

}

-(void)dogParkClient:(DogParkClient *)client didFailWithError:(NSError *)error{
    NSString *errorDescription = [NSString stringWithFormat:@"Request Failed with Error: %@, %@", error, error.userInfo];
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Hundpark"
                               message:errorDescription
                               delegate:nil
                               cancelButtonTitle:@"OK"
                               otherButtonTitles:nil];
    [errorAlert show];
}

- (void)checkStatus
{
    // Get check info (UID and park ID) to send to server as JSON
	NSDictionary *dic =  @{@"UUID": self.UUID,@"parkId": self.park.parkId};
    [client checkStatusForPark:dic];
    
}

-(void)dogParkClient:(DogParkClient *)client didCheckStatus:(id)responseObject;{
    // Parse json
    NSLog(@"%@",responseObject);
    
    
    NSArray *results = responseObject;
    NSDictionary *parkIdDic = [results objectAtIndex:0];
    
    // Check if checked in or not
    if ([parkIdDic[@"checkedIn"] isEqualToString:@"YES"])
    {
        [self.checkInButton setTitle:@"Vovve Inne!" forState:UIControlStateSelected];
        self.checkInButton.selected = YES;
    }
    else if ([parkIdDic[@"checkedIn"] isEqualToString:@"NO"])
    {
        [self.checkInButton setTitle:@"Check In Vovve?" forState:UIControlStateNormal];
        self.checkInButton.selected = NO;
    }
    
}

@end
